<template>
  <div class="app-container">
    <div style="padding:20px 20px 5px 20px;">
      <el-form :inline="true" class="search-form">
        <el-row style="display: flex; flex-wrap: wrap">
          <div style="flex: 1">
            <el-form-item label="活动名称" class="search-form-item" prop="activity_name">
              <el-input clearable placeholder="请输入活动名称" v-model="searchForm.params.name">
              </el-input>
            </el-form-item>
            <el-form-item label="活动状态" class="search-form-item" prop="status">
              <el-select clearable v-model="searchForm.params.status" placeholder="请选择状态">
                <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="生效区域" class="search-form-item" prop="region" v-if="searchDisplay">
              <el-cascader filterable v-model="searchForm.appoint_area_select" style="width: 100%" :options="regionList"
                collapse-tags :props="{
                expandTrigger: 'hover',
                multiple: true,
                value: 'id',
                label: 'name',
                children: 'children',
                checkStrictly: false,
                emitPath: false,
              }" clearable></el-cascader>
            </el-form-item>
            <el-form-item label="用户群组" class="search-form-item" prop="group" v-if="searchDisplay">
              <el-select clearable v-model="searchForm.user_group" multiple collapse-tags placeholder="请选择用户群组">
                <el-option v-for="item in groupingList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="创建时间" class="search-form-item" prop="time" v-if="searchDisplay">
              <el-date-picker v-model="searchForm.time" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right" clearable>
              </el-date-picker>
            </el-form-item>
          </div>
          <div style="margin: 5px 0; text-align: right">
            <el-form-item>
            <el-button @click="getListWay" type="primary" icon="el-icon-search"
              class="inquire-box marginBottom-10">查询</el-button>
            <el-button icon="el-icon-refresh-left" class="reset-box" @click="resetting('searchForm')">重置</el-button>
            <el-button v-if="!searchDisplay" type="warning" icon="el-icon-caret-bottom"
              @click="searchDisplay = true">展开</el-button>
            <el-button v-else type="warning" icon="el-icon-caret-top" @click="searchDisplay = false">收起</el-button>
          </el-form-item>
          </div>
        </el-row>
      </el-form>
    </div>
    <el-divider></el-divider>
    <div class="" style="margin-top: 20px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-button v-hasPermi="'raffle/save'" icon="el-icon-plus" size="small" type="primary"
            @click="addDetail('新建签到')">新建签到活动</el-button>
        </el-col>
        <el-col :span="8" style="float: right">
          <div class="right-panel el-button-group">
            <el-button class="" icon="el-icon-refresh" size="mini" @click="resetting"></el-button>
            <el-dropdown trigger="click" :hide-on-click="false">
              <span class="el-dropdown-link">
                <el-button class="" icon="el-icon-s-operation" size="mini"></el-button>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="fruit in allTableThead" :key="fruit">
                  <el-checkbox v-model="checkboxTableThead" :label="fruit">{{
        tableTheadOptions[fruit].label
      }}</el-checkbox>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-col>
      </el-row>
      <el-col class="marginTop">
        <el-table v-loading="loading" highlight-current-row :data="dataList" :header-cell-style="{
        'background-color': '#f3f8fe',
        color: '#606266',
        height: '50px',
      }" style="width: 100%">
          <el-table-column v-for="fruit in tableThead" :key="fruit" :label="tableTheadOptions[fruit].label"
            min-width="80" align="center">
            <template slot-scope="scope">
              <div v-if="fruit == 'status'">
                <el-tag v-if="scope.row.status == -1" type="danger">活动结束</el-tag>
                <el-tag v-if="scope.row.status == 1" type="success">已开启</el-tag>
                <el-tag v-if="scope.row.status == 2" type="warning">已关闭</el-tag>
                <el-tag v-if="scope.row.status == 3" type="success">进行中</el-tag>
              </div>
              <div v-else>
                <el-tooltip
                  placement="top-start"
                  :content="scope.row[fruit] + ''"
                >
                  <div class="one_line_hidden">
                    {{ scope.row[fruit] ? scope.row[fruit] : "-" }}
                  </div>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="签到记录" align="center">
            <template slot-scope="scope">
              <el-button @click="saveRulesWay(scope.row)" type="text" icon="el-icon-setting">签到记录</el-button>
            </template>
          </el-table-column>
          <el-table-column fixed="right" width="240" prop="address" label="操作" align="center">
            <template slot-scope="scope">
              <el-button v-hasPermi="'raffle/status'" style="margin: 5px"
                v-if="scope.row.status == 1 || scope.row.status == 3" type="warning" size="mini"
                @click="saveStatus(scope.row, 2)">
                关闭活动
              </el-button>
              <el-button v-hasPermi="'raffle/status'" style="margin: 5px" v-if="scope.row.status == 2" type="success"
                size="mini" @click="saveStatus(scope.row, 1)">
                开启活动
              </el-button>
              <el-button v-hasPermi="'raffle/edit'" :disabled="scope.row.status == 1 || scope.row.status == 3" style="margin: 5px" type="primary"
                size="mini" @click="editCoupon(scope.row)">
                编辑
              </el-button>
              <el-popconfirm title="这是一条记录确定删除吗？" @confirm="deleteCoupon(scope.row)">
                <el-button v-hasPermi="'raffle/del'" :disabled="scope.row.status == 1 || scope.row.status == 3" style="margin: 5px" type="danger"
                  size="mini" slot="reference">
                  删除
                </el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col style="text-align: right">
        <pagination v-show="total > 0" :total="total" :page.sync="searchForm.page" :limit.sync="searchForm.count"
          @pagination="getListWay" />
      </el-col>
    </div>

    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="saveVisible" width="700px"
      @close="saveClose">
      <el-row style="position: relative" v-loading="saveLoaidng">
        <el-form :model="saveForm" :rules="saveRules" ref="saveForm" label-width="150px" class="demo-ruleForm">
          <el-col :span="20">
            <el-form-item label="活动名称" prop="sign_name">
              <el-input placeholder="请输入活动名称" v-model="saveForm.sign_name" maxlength="20" show-word-limit></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="20">
            <el-form-item label="时间段" prop="domeTime">
              <el-date-picker @change="domeTimeWay" style="width: 100%" value-format="yyyy-MM-dd" v-model="domeTime"
                type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="排序" prop="sort">
              <el-input @focus="sortFocus" @blur="sortBlur" placeholder="排序" v-model.trim="saveForm.sort" maxlength="5"
                show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="活动说明" prop="explain">
              <el-input placeholder="请输入活动说明" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"
                v-model="saveForm.explain" maxlength="200" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button :loading="saveLoaidng" @click="saveVisible = false">取 消</el-button>
        <el-button :loading="saveLoaidng" type="primary" @click="saveSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 签到记录 -->
    <saveInventory ref="refInventory" />
    <!-- 新建签到抽屉 -->
    <drawer ref="drawer" v-if="ifShowdrawer" :signdetail="signdetail" :regionList="regionList" :gradeList="gradeList"
      :groupingList="groupingList" :TagCategoryAll="TagCategoryAll" :detailTitle="detailTitle" />
  </div>
</template>

<script>
import {
  SaveSign,
  getSignInfo,
  getSignListtwo,
  delSign,
  SaveSignStatus,
  getAwardList,

} from "@/api/activity/index";
import {
  getgroupList,
  getTagCategoryAll,
  getgradeList,
  getRegionList,
} from "@/api/user/index";

import drawer from "./components/drawer";
import saveInventory from "./components/inventory.vue";

const tableTheadOption = {
  id: {
    label: "活动编号",
    field: "id",
  },
  created_at: {
    label: "创建时间",
    field: "created_at",
  },
  sign_name: {
    label: "签到活动名称",
    field: "sign_name",
  },
  start_time: {
    label: "开始时间",
    field: "start_time",
  },
  end_time: {
    label: "结束时间",
    field: "end_time",
  },
  sort: {
    label: "排序",
    field: "sort",
  },
  status: {
    label: "状态",
    field: "status",
  },
};
const allTableThead = [
  "id",
  "created_at",
  "sign_name",
  "start_time",
  "end_time",
  "status",
];
const defaultTableThead = [
  "created_at",
  "sign_name",
  "start_time",
  "end_time",
  "status",
];
export default {
  watch: {
    checkboxTableThead(valArr) {
      this.tableThead = this.allTableThead.filter(
        (i) => valArr.indexOf(i) >= 0
      );
      this.tableKey = this.tableKey + 1;
    },
  },
  components: {
    drawer,
    saveInventory
  },
  data() {
    return {
      signdetail:{},//签到详情
      searchDisplay:false,
      // 动态显示表头默认表头
      tableTheadOptions: tableTheadOption,
      allTableThead: allTableThead,
      tableThead: defaultTableThead, // 默认表头
      checkboxTableThead: defaultTableThead, // 默认表头值
      tableKey: 1, // 为了保证table 每次都会重渲
      loading: false,
      ifShowdrawer: false, //是否打开详情抽屉
      detailTitle: "", //抽屉标题
      regionList: [],//生效区域
      groupingList: [],//用户群组
      status: [
        { name: "已过期", id: -1 },
        { name: "已开启", id: 1 },
        { name: "进行中", id: 3 },
        { name: "已关闭", id: 2 },
      ],
      searchForm: {
        page: 1,
        count: 10,
        params:{
          name:'',
          status:''// 状态状态：-1过期 1开启 2进行中 3关闭
        },
        appoint_area_select: [], //生效区域
        user_group: [], //用户群组
        time: [], //创建时间
      },
      total: 0,
      dataList: [],
      title: "添加活动",
      saveVisible: false,
      saveLoaidng: false,
      saveForm: {
        sign_name: "",
        start_time: "",
        end_time: "",
        explain: "",
        sort: 0,
        id: "",
      },
      domeTime: [],
      saveRules: {
        sign_name: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let req = /[^0-9a-zA-Z\u4e00-\u9fa5]/g;
              if (!value) {
                callback(new Error("请输入活动名称"));
              } else {
                if (req.test(value)) {
                  callback(new Error("活动名称中不能存在特殊字符"));
                } else {
                  callback();
                }
              }
            },
            trigger: "change",
          },
        ],
        domeTime: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.domeTime.length == 0) {
                return callback(new Error("请选择活动的时间段"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        explain: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value == "") {
                return callback(new Error("请输入活动说明"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    const p1 = new Promise((resolve, reject) => {
      getgroupList().then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.$messages.error(res.msg);
          reject();
          return;
        }
        this.groupingList = res.data.list;
        resolve();
      });
    });

    const p2 = new Promise((resolve, reject) => {
      getTagCategoryAll().then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.$messages.error(res.msg);
          reject();
          return;
        }
        this.TagCategoryAll = res.data;
        resolve();
      });
    });

    const p3 = new Promise((resolve, reject) => {
      getgradeList().then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.$messages.error(res.msg);
          reject();
          return;
        }
        this.gradeList = res.data.list;
        resolve();
      });
    });

    const p4 = new Promise((resolve, reject) => {
      getRegionList({ level: 2 }).then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.$messages.error(res.msg);
          reject();
          return;
        }
        this.regionList = res.data;
        console.log(this.regionList)
        resolve();
      });
    });
    Promise.all([p1, p2, p3, p4])
      .then(() => {
        this.getListWay();
      })
      .catch(() => {
        this.loading = false;
      });
  },
  methods: {
    getListWay() {
      this.loading = true;
      let searchObj = {
        params:{
          name:this.searchForm.params.name,
          status:this.searchForm.params.status
        },
        page: this.searchForm.page,
        count: this.searchForm.count,
        // appoint_area_select: this.searchForm.appoint_area_select.toString(),
        // user_group: this.searchForm.user_group.toString(),
      };
      if (this.searchForm.time.length !== 0) {
        searchObj.start_time =
          this.searchForm.time.length !== 0 ? this.searchForm.time[0] : "";
        searchObj.end_time =
          this.searchForm.time.length !== 0 ? this.searchForm.time[1] : "";
      } else {
        searchObj.start_time = "";
        searchObj.end_time = "";
      }
      getSignListtwo(searchObj).then((res) => {
        this.loading = false;
        if (res.code !== 200 || res.status !== 1) {
          this.loading = false;
          return this.$messages.error(res.msg);
        }
        this.dataList = res.data.list;
        this.total = res.data.total;
      });
    },
    resetting() {
      this.searchForm = {
        params:{
           name: "", // 签到活动名称
           status: "", // 状态状态：-1过期 1开启 2进行中 3关闭
        },
        appoint_area_select: [], //生效区域
        user_group: [], //用户群组

        time: [],
        page: 1,
        count: 10,
      };
      this.getListWay();
    },
    saveStatus(row, num) {
      var obj = {
        id: row.id,
        status: num,
      };
      this.loading = true;
      SaveSignStatus(obj)
        .then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.loading = false;
            return this.$messages.error(res.msg);
          }
          this.$messages.success("操作成功");
          this.getListWay();
        })
        .catch((err) => {
          this.$messages.error(err.msg);
          this.loading = false;
        });
    },
    deleteCoupon(row) {
      this.loading = true;
      delSign({ id: row.id })
        .then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.loading = false;
            return this.$messages.error(res.msg);
          }
          this.$messages.success("删除成功");
          this.getListWay();
        })
        .catch((err) => {
          this.loading = false;
          this.$messages.error(err.msg);
        });
    },
    saveRulesWay(row) {
      this.$refs.refInventory.open(row)
    },
    saveClose() {
      this.saveForm = {
        sign_name: "",
        start_time: "",
        end_time: "",
        explain: "",
        sort: 0,
        id: "",
      };
      this.domeTime = [];
      if (this.$refs.saveForm) {
        this.$refs.saveForm.resetFields();
      }
    },
    editCoupon(row) {
      this.ifShowdrawer = true;
      getSignInfo({ id: row.id })
        .then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.$messages.error(res.msg);
            return;
          }
          this.signdetail = res.data
          this.$refs.drawer.signdetails(res.data)
          // console.log(res.data)
        })
        .catch(() => {
        });
    },

    //打开抽屉
    addDetail(title) {
      this.detailTitle = title;
      this.ifShowdrawer = true;
    },
    //关闭抽屉
    closedetail() {
      this.ifShowdrawer = false;
      this.getListWay();
    },

    domeTimeWay(val) {
      if (val.length !== 0) {
        this.saveForm.start_time = val[0];
        this.saveForm.end_time = val[1];
      } else {
        this.saveForm.start_time = "";
        this.saveForm.end_time = "";
      }
    },
    sortFocus() {
      if (this.saveForm.sort == 0) {
        this.saveForm.sort = "";
      }
    },
    sortBlur() {
      if (this.saveForm.sort == "") {
        this.saveForm.sort = 0;
      }
    },
    saveSubmit() {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.saveLoaidng = true;
          SaveSign(this.saveForm).then((res) => {
            this.saveLoaidng = false;
            if (res.code !== 200 || res.status !== 1) {
              this.$messages.error(res.msg);
              return;
            }
            this.$messages.success(res.msg);
            this.saveClose();
            this.saveVisible = false;
            this.getListWay();
          });
          console.log(this.saveForm);
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss"></style>
<style lang="scss" scoped></style>
